package com.xyxy.platform.website.member.web.controller;

import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.bind.annotation.CurrentUser;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.IsDelete;
import com.xyxy.platform.modules.entity.common.SysArea;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.entity.finance.AccountLog;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImagePkg;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.member.*;
import com.xyxy.platform.modules.service.common.address.AddressService;
import com.xyxy.platform.modules.service.content.ArticleService;
import com.xyxy.platform.modules.service.finance.FinanceService;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.member.*;
import com.xyxy.platform.modules.service.member.vo.MemberDetail;
import com.xyxy.platform.website.common.constants.AppConstants;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yangdianjun on 15/12/15.
 */
@Controller
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Autowired
    private AddressService addressService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private FinanceService financeService;
    @Autowired
    private MemberSpecificTagService memberSpecificTagService;
    @Autowired
    private SpecificTagService specificTagService;
    @Autowired
    private MemberProfessionService memberProfessionService;
    @Autowired
    private ProfessionService professionService;
    @Autowired
    private ImageItemService imageItemService;
    @Autowired
    private SystemFileService systemFileService;


    @RequestMapping("/")
    public String index(@CurrentUser CurrentLoginUser user, Model model) {
        List list = addressService.getListProvince();
        request.setAttribute("provincelist", list);
        MemberDetail member = memberService.findMemberDetailById(user.getId());
        request.setAttribute("memberDetail", member);
        if (member.getMember().getArticleId() == null) {
            Article a = new Article();
            a.setIsDel(1);
            a.setTitle("自我介绍");
            a.setArticleTypeId(1);
            a.setCreateTime(new Date());
            a.setContent("");
            articleService.insertArticle(a);
            member.getMember().setArticleId(a.getArticleId());
        }
        if (StringUtils.isNoneBlank(member.getMember().getAddress())) {
            List<SysArea> sysAreaList = addressService.getPathArea(Integer.parseInt
                    (member.getMember().getAddress()));
            request.setAttribute("sysAreaList", sysAreaList);
        }
        return "member/info";
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public boolean update(Member member, String article, String imgurl, @CurrentUser CurrentLoginUser user) throws ParseException {
        Article article1 = new Article();
        article1.setIsDel(IsDelete.NO.ordinal());
        article1.setArticleId(member.getArticleId());
        article1.setContent(article);
        articleService.update(article1);

        member.setArticleId(article1.getArticleId());
        member.setId(user.getId());
        //头像
        if (StringUtils.isNotBlank(imgurl)) {
            Long imagePkgId = member.getImagePkgId();
            if (null == imagePkgId) {
                ImagePkg imagePkg = new ImagePkg();
                imageItemService.insertImagePkg(imagePkg);
                imagePkgId = imagePkg.getId();
            }
            String fileName = systemFileService.getFileNameFromUrl(imgurl);
            List<ImageItem> itemList = imageItemService.findImageItemList(imagePkgId, ImageTypes.USER_ICON);
            if(Collections3.isNotEmpty(itemList)){
                itemList.get(0).setUri(fileName);
                imageItemService.updateUri(itemList.get(0));
            }else{
                ImageItem item = new ImageItem();
                item.setImagePkgId(imagePkgId);
                item.setImageTypeId(ImageTypes.USER_ICON.getTypeId());
                item.setUri(fileName);
                imageItemService.insert(item);
                member.setImagePkgId(imagePkgId);
            }
        }
        if (memberService.updateMemebrInfoById(member)) {
            CurrentLoginUser currentLoginUser =new CurrentLoginUser(member.getId(), member.getAlias());
            if(StringUtils.isNoneBlank(imgurl)){
                currentLoginUser.setImageUrl(imgurl);
            }
            request.getSession().setAttribute(AppConstants.CURRENT_USER, currentLoginUser);
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/ mywallet")
    public String getmywallet(@CurrentUser CurrentLoginUser user) {
        AccountLog accountLog = financeService.getMyAccount(user.getId());
        request.setAttribute("myaccount", accountLog);
        return "member/wallet";
    }

    @RequestMapping(value = "/label")
    public String label(@CurrentUser CurrentLoginUser user) {
        List<MemberSpecificTag> specificTagList =
                memberSpecificTagService.findByMemberId(user.getId());
        List<SpecificTag> spetagList = new ArrayList<>();
        if (specificTagList.size() != 0) {
            for (MemberSpecificTag m : specificTagList) {
                SpecificTag source = specificTagService.findById(m.getSpecificId());
                source.setMemberSpecificTagId(m.getId());
                spetagList.add(source);
            }
        }
        List<MemberProfession> professionList = memberProfessionService.findByMemberId
                (user.getId());
        List<Profession> prolist = new ArrayList<>();
        if (professionList.size() != 0) {
            for (MemberProfession m : professionList) {
                Profession source = professionService.findById(m.getProfessionId());
                source.setProfessionMemberId(m.getId());
                prolist.add(source);
            }
        }
        request.setAttribute("SpecificTagList", spetagList);
        request.setAttribute("ProfessionList", prolist);
        return "member/label";
    }

    @ResponseBody
    @RequestMapping(value = "/deleteprofession")
    public ResponseMessage<?> deleteprofession(@CurrentUser CurrentLoginUser user,
                                               Profession profession) {
        if (profession != null && profession.getId() != null) {
            Long memberId = user.getId();
            memberProfessionService.deleteByPrimaryKey
                    (profession.getProfessionMemberId());
            professionService.deleteById(profession.getId());
            return ResponseUtils.jsonSuccess(true);
        }
        return ResponseUtils.jsonFail(false, "删除失败请重试");
    }

    @ResponseBody
    @RequestMapping(value = "/deletespecifitag")
    public ResponseMessage<?> deletespecifitag(@CurrentUser CurrentLoginUser user,
                                               SpecificTag specificTag) {
        if (specificTag != null && specificTag.getId() != null) {
            Long memberId = user.getId();
            memberSpecificTagService.deleteByPrimaryKey
                    (specificTag.getMemberSpecificTagId());
            specificTagService.deleteById(specificTag.getId());
            return ResponseUtils.jsonSuccess(true);
        }
        return ResponseUtils.jsonFail(false, "删除失败请重试");
    }

    @ResponseBody
    @RequestMapping(value = "/addprofession", method = RequestMethod.POST)
    public ResponseMessage<?> addspecifi(@CurrentUser CurrentLoginUser user, String
            tagName) {
        if(StringUtils.isBlank(tagName)){
            return ResponseUtils.jsonFail(false,"标签不能为空");
        }
        Profession pro = new Profession();
        pro.setName(tagName);
        Profession source = professionService.findByName(tagName);
        if (source == null) {
            professionService.create(pro);
            memberProfessionService.create(pro, user.getId());
        } else {
            pro.setId(source.getId());
            MemberProfession memberProfession = new MemberProfession();
            memberProfession.setMemberId(user.getId());
            memberProfession.setProfessionId(pro.getId());
            MemberProfession memberProfessionSource =memberProfessionService.findByTagName(memberProfession);
            if(!(memberProfessionSource==null)){
                return ResponseUtils.jsonFail(false,"已存在该标签，不能重复添加");
            }
            memberProfessionService.create(pro, user.getId());
        }
        return ResponseUtils.jsonSuccess(true, "");
    }

    @ResponseBody
    @RequestMapping(value = "/addspecifi", method = RequestMethod.POST)
    public ResponseMessage<?> addprofession(@CurrentUser CurrentLoginUser user, String
            tagName) {
        if(StringUtils.isBlank(tagName)){
            return ResponseUtils.jsonFail(false,"标签不能为空");
        }
        SpecificTag spc = new SpecificTag();
        spc.setName(tagName);
        SpecificTag source = specificTagService.findByName(tagName);
        if (source == null) { //当前标签不存在
            specificTagService.create(spc);
            memberSpecificTagService.create(spc, user.getId());
        } else {
            spc.setId(source.getId());
            MemberSpecificTag memberSpecificTag=new MemberSpecificTag();
            memberSpecificTag.setMemberId(user.getId());
            memberSpecificTag.setSpecificId(spc.getId());
            MemberSpecificTag memberSpecificTagSource = memberSpecificTagService.findByTagName(memberSpecificTag);
            if(!(memberSpecificTagSource==null)){
                return ResponseUtils.jsonFail(false,"已存在该标签，不能重复添加");
            }
            memberSpecificTagService.create(spc, user.getId());
        }




        return ResponseUtils.jsonSuccess(true, "");
    }

    @RequestMapping(value = "/password", method = RequestMethod.GET)
    public String password() {
        return "member/password";
    }

    @ResponseBody
    @RequestMapping(value = "/password", method = RequestMethod.POST)
    public ResponseMessage<?> password(String password, String newpassword,
                                       @CurrentUser CurrentLoginUser user) {
        Member source = memberService.findMemberDetailById(user.getId()).getMember();
        if (source.getPassword().equals(password)) {
            Member target = new Member();
            target.setId(user.getId());
            target.setPassword(newpassword);
            return memberService.updateMemebrInfoById(target) ?
                    ResponseUtils.jsonSuccess(true, "修改成功") : null;
        }
        return ResponseUtils.jsonFail(false, "当前密码错误");
    }

    @RequestMapping(value = "/contact", method = RequestMethod.GET)
    public String contact(@CurrentUser CurrentLoginUser user) {
        Member source = memberService.findMemberDetailById(user.getId()).getMember();
        String mobile = source.getMobile();
        String qq = source.getQq();
        request.setAttribute("mobile", mobile);
        request.setAttribute("qq", qq);
        return "member/contact";
    }

    @ResponseBody
    @RequestMapping(value = "/contact", method = RequestMethod.POST)
    public ResponseMessage<?> contact(Member member, @CurrentUser CurrentLoginUser
            user) {
        member.setId(user.getId());
        boolean b = memberService.updateMemebrInfoById(member);
        if (b) {
            return ResponseUtils.jsonSuccess("修改成功");
        }
        return ResponseUtils.jsonFail(false, "修改失败");
    }


    @RequestMapping(value = "/headpic", method = RequestMethod.GET)
    public String headpic(@CurrentUser CurrentLoginUser user) {
        return "member/headpic";
    }


}

